import os
import json
import sqlite3
from .. import config

script_dir = os.path.dirname(os.path.abspath(__file__))


class ConfigDatabase:
    """SQLite 数据库管理类"""

    def __init__(self, db_path=None):
        if db_path is None:
            # 数据库文件现在应该在项目根目录，而不是 src 目录
            db_path = os.path.join(os.path.dirname(os.path.dirname(script_dir)), config.config_db)
        self.db_path = db_path
        self.conn = sqlite3.connect(self.db_path)
        self.init_database()

    def close(self):
        """关闭数据库连接"""
        if self.conn:
            self.conn.close()

    def init_database(self):
        """初始化数据库表结构"""
        cursor = self.conn.cursor()

        # 创建配置表
        cursor.execute(
            """
            CREATE TABLE IF NOT EXISTS config (
                key TEXT PRIMARY KEY,
                value TEXT
            )
        """
        )

        # 创建历史记录表
        cursor.execute(
            """
            CREATE TABLE IF NOT EXISTS history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                mode TEXT NOT NULL,
                path TEXT NOT NULL,
                settings TEXT NOT NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                last_used DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        """
        )

        # 创建默认设置表
        cursor.execute(
            """
            CREATE TABLE IF NOT EXISTS default_settings (
                mode TEXT PRIMARY KEY,
                settings TEXT NOT NULL
            )
        """
        )

        # 创建唯一索引
        cursor.execute(
            """
            CREATE UNIQUE INDEX IF NOT EXISTS idx_history_mode_path
            ON history(mode, path)
        """
        )

        self.conn.commit()

    def get_config(self, key, default=None):
        """获取配置值"""
        cursor = self.conn.cursor()
        cursor.execute("SELECT value FROM config WHERE key = ?", (key,))
        result = cursor.fetchone()
        if result:
            try:
                return json.loads(result[0])
            except json.JSONDecodeError:
                return result[0]
        return default

    def set_config(self, key, value):
        """设置配置值"""
        cursor = self.conn.cursor()
        if isinstance(value, (dict, list)):
            value = json.dumps(value, ensure_ascii=False)
        cursor.execute(
            "INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)", (key, value)
        )
        self.conn.commit()

    def get_history(self, mode):
        """获取指定模式的历史记录"""
        cursor = self.conn.cursor()
        cursor.execute(
            """
            SELECT path, settings FROM history
            WHERE mode = ?
            ORDER BY last_used DESC
            LIMIT ?
        """,
            (mode, self.get_max_history_records()),
        )

        results = []
        for row in cursor.fetchall():
            path, settings_json = row
            try:
                settings = json.loads(settings_json)
                settings["path"] = path
                results.append(settings)
            except json.JSONDecodeError:
                continue
        return results

    def save_history(self, mode, path, settings):
        """保存历史记录"""
        # 从 settings 中移除 path，因为它作为单独字段存储
        settings_copy = settings.copy()
        if "path" in settings_copy:
            del settings_copy["path"]

        settings_json = json.dumps(settings_copy, ensure_ascii=False)

        cursor = self.conn.cursor()
        # 使用 UPSERT 操作
        cursor.execute(
            """
            INSERT INTO history (mode, path, settings, last_used)
            VALUES (?, ?, ?, CURRENT_TIMESTAMP)
            ON CONFLICT(mode, path)
            DO UPDATE SET
                settings = excluded.settings,
                last_used = CURRENT_TIMESTAMP
        """,
            (mode, path, settings_json),
        )

        # 删除超出限制的旧记录
        cursor.execute(
            """
            DELETE FROM history
            WHERE mode = ? AND id NOT IN (
                SELECT id FROM history
                WHERE mode = ?
                ORDER BY last_used DESC
                LIMIT ?
            )
        """,
            (mode, mode, self.get_max_history_records()),
        )

        self.conn.commit()

    def get_default_settings(self, mode):
        """获取默认设置"""
        cursor = self.conn.cursor()
        cursor.execute("SELECT settings FROM default_settings WHERE mode = ?", (mode,))
        result = cursor.fetchone()
        if result:
            try:
                return json.loads(result[0])
            except json.JSONDecodeError:
                pass

        # 返回硬编码的默认值
        if mode == "scan":
            return {
                "wanted_dirs": config.wanted_dirs,
                "hated_dirs": config.hated_dirs,
                "include_files": [],
                "keil_base_arguments": config.keil_base_arguments,
                "use_relative_path": True,
            }
        else:  # keil
            return {
                "keil_base_arguments": config.keil_base_arguments,
                "keil_include_dirs": [],
                "include_files": [],
                "root_path": "",
                "use_relative_path": True,
            }

    def set_default_settings(self, mode, settings):
        """设置默认设置"""
        settings_json = json.dumps(settings, ensure_ascii=False)
        cursor = self.conn.cursor()
        cursor.execute(
            "INSERT OR REPLACE INTO default_settings (mode, settings) VALUES (?, ?)",
            (mode, settings_json),
        )
        self.conn.commit()

    def migrate_from_json(self, json_path):
        """从 JSON 配置文件迁移数据"""
        if not os.path.exists(json_path):
            return

        try:
            with open(json_path, "r", encoding="utf-8") as f:
                old_config = json.load(f)

            # 迁移基本配置
            if "last_mode" in old_config:
                self.set_config("last_mode", old_config["last_mode"])

            # 迁移历史记录
            scan_history = old_config.get("scan_history", [])
            for item in scan_history:
                if isinstance(item, dict) and "path" in item:
                    self.save_history("scan", item["path"], item)

            keil_history = old_config.get("keil_history", [])
            for item in keil_history:
                if isinstance(item, dict) and "path" in item:
                    self.save_history("keil", item["path"], item)

            # 迁移默认设置
            default_settings = old_config.get("default_settings", {})
            if "scan" in default_settings:
                self.set_default_settings("scan", default_settings["scan"])
            if "keil" in default_settings:
                self.set_default_settings("keil", default_settings["keil"])

            # 重命名旧文件作为备份
            backup_path = json_path + ".backup"
            if not os.path.exists(backup_path):
                os.rename(json_path, backup_path)

        except (json.JSONDecodeError, IOError) as e:
            print(f"迁移配置文件时出错: {e}")

    def clean_invalid_history(self):
        """清理包含占位符文本或无效路径的历史记录"""
        placeholder_texts = [
            "选择或拖入 Keil 项目文件或工作区目录",
            "Select or drag Keil project file or workspace directory",
            "",  # 空字符串
        ]

        cursor = self.conn.cursor()

        # 删除包含占位符文本的记录
        for placeholder in placeholder_texts:
            cursor.execute("DELETE FROM history WHERE path = ?", (placeholder,))

        self.conn.commit()

    def get_max_history_records(self):
        """获取最大历史记录数"""
        return self.get_config(
            "max_history_records", config.DEFAULT_MAX_HISTORY_RECORDS
        )

    def set_max_history_records(self, value):
        """设置最大历史记录数"""
        self.set_config("max_history_records", value)


# 创建全局数据库实例
db = ConfigDatabase()
